#!/usr/bin/env python    
#encoding: utf-8  
import binascii   

def remap_little_big(old):
    return old[6:8] + old[4:6] + old[2:4] + old[0:2]

def bin2coe(input_file,output_file):
    fh = open(input_file, 'rb')  
    a = fh.read() 
    #print 'raw: ',`a`,type(a)  
    hexstr = binascii.b2a_hex(a)
    # print (a)
    i = 0
    txt = hexstr.decode()

    with open(output_file, 'wt') as f:
        print("memory_initialization_radix=16;",file=f)
        print("memory_initialization_vector="  ,file=f)
        while i<len(txt):
            if i + 16 >= len(txt):
                ch = ';'
            else:
                ch = ','
            print(remap_little_big(txt[i+8 : i+16]) + remap_little_big(txt[i : i+8]) + ch,file=f)
            i = i + 16


def bin2tbMem(input_file,output_file):
    fh = open(input_file, 'rb')  
    a = fh.read() 
    #print 'raw: ',`a`,type(a)  
    hexstr = binascii.b2a_hex(a)
    # print (a)
    i = 0
    txt = hexstr.decode()

    with open(output_file, 'wt') as f:
        while i<len(txt):
            print(remap_little_big(txt[i+8 : i+16]) + remap_little_big(txt[i : i+8]),file=f)
            i = i + 16

def checkNumCulate(data):
    sum = 0
    for i in range(0,24,2):
        sum += int(data[i:i+2],16)
    out_ = 256 - (sum % 256)
    if out_ == 256:
        out_ = 0
    return "%02X"%out_

def bin2IntelHex(input_file,output_file):
    fh = open(input_file, 'rb')  
    a = fh.read() 
    #print 'raw: ',`a`,type(a)  
    hexstr = binascii.b2a_hex(a)
    # print (a)
    i = 0
    txt = hexstr.decode()
    addr = 0
    with open(output_file, 'wt') as f:
        while i<len(txt):
            t = "08%04X00"%addr
            t += remap_little_big(txt[i+8 : i+16]) + remap_little_big(txt[i : i+8])
            if len(t) < 24:
                t += '0' * (24 - len(t)) 
            t += checkNumCulate(t)
            i = i + 16
            addr = addr + 1
            # print("%s"%t)
            print(":" + t,file=f)
        print(":00000001FF",end="",file=f)